﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BoAoCoffee.Model
{
    /// <summary>
    /// 咖啡通讯
    /// </summary>
    public class coffeeMsg
    {
        private static coffeeMsg instance;
        private coffeeMsg() { }

        public static coffeeMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new coffeeMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
#pragma warning disable CS0414 // 字段“coffeeMsg.nostrs”已被赋值，但从未使用过它的值
        string nostrs = "";
#pragma warning restore CS0414 // 字段“coffeeMsg.nostrs”已被赋值，但从未使用过它的值
        public Thread All_thr;
        public bool isMaking = false;
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.CoffeePortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                CoffeeSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.CoffeePortName, 115200, "", 8, 1);//其他串口通讯
                CoffeeSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                All_thr = new Thread(AllMessages);
                All_thr.IsBackground = true;
                All_thr.Start();
            }
            catch (Exception)
            {
                CoffeeSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(200);
                IOSerial_Thr();
            }
        }
        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                            CoffeeSerialPort.Instance.SerialSend(CoffeeMake.TypeCoffee);
                        Thread.Sleep(500);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(500);
                    }

                }
            }
            catch (Exception)
            {
                CoffeeSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(200);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                var ddd = CoffeeSerialPort.Instance.serialPort.BytesToRead;
                byte[] result = new byte[ddd];
                CoffeeSerialPort.Instance.serialPort.Read(result, 0, ddd);
                buffer.AddRange(result);
                string str = "";// $"{DateTime.Now}：\n";
                                //判断读写模式
                if (buffer.Count > 0x03)
                    str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                //Console.WriteLine(str);
                MsgShow(str);
                Thread.Sleep(1);


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex + " " + DateTime.Now.ToString());
                return;
            }
        }
        string zblist = "";
        public bool IsJBol = false;
        public void MsgShow(string str)
        {
            try
            {
                var note = str.Split(' ');
                if (note[0].Length > 2)
                {
                    string note1 = note[0].Substring(note[0].Length - 2, 2);
                    if (zblist.Length >= 78)
                    {
                        zblist = "";
                    }
                    if (note1 == "7E")
                    {
                        zblist = note1 + " ";
                    }
                    else if (zblist != "")
                        zblist += note1 + " ";
                    if (zblist != "")
                    {
                        for (int i = 1; i < note.Count(); i++)
                        {
                            if (note[i] != "")
                                zblist += note[i] + " ";
                        }
                    }
                    var nos = zblist.Split(' ');
                  //  Console.WriteLine(zblist);
                    if (zblist.Length >= 78)
                    {
                        if (Instance.AllBol)
                        {
                            //Console.WriteLine(str);
                            var cf = zblist.Split(' ');
                            if (cf.Count() >= 26)
                            {
                                // Console.WriteLine(cf[18]);
                                Instance.isMaking = cf[18] == "02" && cf[3] != "08";
                                if (WuLiaoCoffeeSel.Instance.CoffeeBean_Sel_Bol != (cf[3] != "08"))
                                {
                                    WuLiaoCoffeeSel.Instance.CoffeeBean_Sel_Bol = cf[3] != "08";
                                    IsJBol = cf[18] == "04";
                                    ClientList clientList = new ClientList();
                                    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                                    clientList.code = 2;
                                    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
        #endregion
    }
}
